var bxt = require('bxt.js')
var base64 = require('base64.js')
var md5 = require('md5.js')
var sha1 = require('hmac_sha1.js')

function uploadImage(path, catalogue, success, fail) {
  var saveKey = path.split('tmp')[1]
  var date = (new Date()).toGMTString()
  
  let task = null, videoThumbnail = ''
  if (catalogue == bxt.UP_YUN_VIDEO_PATH) {
    videoThumbnail = '/videos/images/' + saveKey + '.png'
    task = [{
      "name": "naga",
      "type": 'thumbnail',
      "avopts": "/o/true/n/1",
      "return_info": true,
      'save_as': videoThumbnail
    }]
  }
  
  var opts = {
    'save-key': catalogue + saveKey,
    bucket: bxt.UP_YUN_BUCKET,
    expiration: Math.round(new Date().getTime() / 1000) + 3600,
    date: date
  }

  if (task) { // 生成视频缩略图
    opts.apps = task
  }

  var policy = base64.encode(JSON.stringify(opts))

  var data = ['POST', '/' + bxt.UP_YUN_BUCKET, date, policy].join('&')
  var signature = sha1(md5.hexMD5(bxt.UP_YUN_PASSWORD), data)

  wx.uploadFile({
    url: bxt.UP_YUN_API,
    filePath: path,
    name: 'file',
    formData: {
      authorization: 'UPYUN ' + bxt.UP_YUN_OPERATOR + ':' + signature,
      policy: policy
    },
    success: function (res) {
      // 检查图片是否上传成功
      console.log(res)
      if (200 == res.statusCode) {
        success(bxt.UP_YUN_IMAGE_DOMAIN + catalogue + saveKey, bxt.UP_YUN_IMAGE_DOMAIN + videoThumbnail)
      }else {
        fail('图片上传失败')
      }
    },
    fail: function (res) {
      fail('图片上传失败')
    }
  })
}

module.exports.uploadImage = uploadImage